<template>
  <div class="login-container">
    <div class="login-box">
      <div class="brand">
        <img src="@/assets/logo.svg" alt="logo" class="brand-logo" />
        <h2 class="login-title">系统登录</h2>
      </div>
      <el-form 
        ref="formRef"
        :model="form" 
        :rules="rules"
        label-position="top"
        @keyup.enter="onSubmit"
      >
        <el-form-item prop="userName" label="用户名">
          <el-input 
            v-model="form.userAccount"
            prefix-icon="User"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input 
            type="password" 
            v-model="form.userPassword" 
            prefix-icon="Lock"
            placeholder="请输入密码"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item>
          <div class="remember-row">
            <el-checkbox v-model="form.remember">记住密码</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码?</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="onSubmit" 
            :loading="loading"
            class="submit-btn"
          >登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
// @ts-ignore
import {Read,Write,getReadClient} from '@/Urls/AxiosHelper'
import { ElMessage } from 'element-plus'
// @ts-ignore
import {useCounterStore} from '@/stores/counter'
import { useRouter,useRoute } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'

const store=useCounterStore()
const router=useRouter()
const route=useRoute()
const formRef = ref()
const loading = ref(false)

// 表单数据
const form = reactive({
  userAccount: "",
  userPassword: "",
  remember: false
})

// 表单验证规则
const rules = reactive({
  userAccount: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3到20个字符', trigger: 'blur' }
  ],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ]
})

// 检查本地存储的登录信息
onMounted(() => {
  const savedUserName = localStorage.getItem('rememberedUserName')
  const savedPassword = localStorage.getItem('rememberedPassword')
  
  if (savedUserName && savedPassword) {
    form.userAccount = savedUserName
    form.userPassword = savedPassword
    form.remember = true
  }
})

const onSubmit = () => {
  if (!formRef.value) return
  
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      login()
    }
  })
}

const login = () => {
  loading.value = true
  
  // 使用最后一个读接口（索引4，对应端口5267）
  const readClient = getReadClient(4)
  
  readClient({
    url:'sysread/api/User/Login',
    method:'post',
    data:form
  }).then((res)=>{
    loading.value = false
    console.log(res.data);
    if(res.data.code==200){
      // 保存用户信息到store
      store.User.RoleNo=res.data.data.roleNo
      store.User.RoleName=res.data.data.roleName
      store.User.UserNo=res.data.data.userNo
      store.User.UserName=res.data.data.userAccount
      store.User.UserNickName=res.data.data.userName
      store.User.Token=res.data.data.token
      
      // 保存token到localStorage
      localStorage.setItem("token", res.data.data.token)
      
      // 如果选择了记住密码，保存登录信息
      if (form.remember) {
        localStorage.setItem('rememberedUserName', form.userAccount)
        localStorage.setItem('rememberedPassword', form.userPassword)
      } else {
        localStorage.removeItem('rememberedUserName')
        localStorage.removeItem('rememberedPassword')
      }
      
      ElMessage.success("登录成功")
      router.push('/Main')
    } else {
      ElMessage.error("用户名或密码错误")
    }
  }).catch(error => {
    loading.value = false
    ElMessage.error('登录失败，请稍后重试')
  })
}
</script>

<style scoped>
.login-container {
  position: fixed;
  inset: 0; /* 顶部、底部、左右全贴合浏览器 */
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #e8f0ff 0%, #f7fbff 100%);
  padding: 16px; /* 小边距防止超小屏贴边 */
}

.login-box {
  width: 420px;
  max-width: 100%;
  padding: 36px 36px 28px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  border: 1px solid #eef1f6;
}

.brand{
  display:flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}
.brand-logo{ width:56px; height:56px; }

.login-title {
  text-align: center;
  margin-bottom: 22px;
  color: #1556F0;
  font-weight: 500;
}

.remember-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.submit-btn {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}

@media (max-width: 480px){
  .login-box{ width: 100%; padding: 24px; }
}
</style>
